package cn.toe.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.toe.bean.Article;
import cn.toe.bean.Astyle;
import cn.toe.service.ArticleService;
import cn.toe.service.AstyleService;
import cn.toe.utils.FileUtils;

@Controller
@RequestMapping("/article")
public class ArticleController {
	
	@Autowired
	private ArticleService articleService;
	
	@Autowired
	private AstyleService astyleService;
	
	@RequestMapping("/toAddArticle")
	public String addArticle(HttpServletRequest request){
		List<Astyle> astyles = astyleService.getAllAstyle();
		request.setAttribute("astyles", astyles);
		return "jsp/Article/addArticle";
	}
	
	@RequestMapping("/addArticle")
	public void addArticle(Article article,String content,HttpServletRequest request,Integer astyle){
		article.setAstyle(astyleService.getAstyle(astyle));
		articleService.addArticle(article);
		String filename = request.getRealPath("./")+"files\\article\\" + article.getArticleId() + "_articleContent.txt";
		String filename2 = "C:\\Users\\Administrator\\git\\weixinproject\\weixinproject\\WebRoot\\files\\article\\" + article.getArticleId() + "_articleContent.txt";
		File f = new File(filename);
		if (!f.exists()) {
			try {
				f.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
		File f2 = new File(filename2);
		if (!f2.exists()) {
			try {
				f2.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
		FileUtils.writeFile(filename, content);
		FileUtils.writeFile(filename2, content);
		String file = "/weixin/files/article/" + article.getArticleId() + "_articleContent.txt";
		article.setArticleContent(file);
		articleService.updateArticle(article);
	}
	
	@RequestMapping("/getAllArticle")
	public String getAllArticle(HttpServletRequest request){
		List<Article> articles = articleService.getAllArticle();
		request.setAttribute("articles", articles);
		return "jsp/Article/articleManager";
	}
	
	@RequestMapping("getArticle")
	public String getArticle(Integer id,HttpServletRequest request){
		Article article = articleService.getArticle(id);
		System.out.println(article.getTitle());
		request.setAttribute("article",article);
		return "jsp/Article/articleContent";
	} 
	
	@RequestMapping("/updateArticle")
	public String updateUser(Article article,HttpServletRequest request){
		if(articleService.updateArticle(article)){
			request.setAttribute("article", article);
			return "/editplanet";
		}else{
			return "/error";
		}
	}
}
